// 自定义 MediaPipe 骨架绘制工具，便于在不同组件中复用

export interface StylizedPoseOptions {
  visibilityThreshold?: number;
  lineWidth?: number;
  pointRadius?: number;
  gradientStops?: Array<{ offset: number; color: string }>;
}

interface Landmark {
  x: number;
  y: number;
  z?: number;
  visibility?: number;
}

const DEFAULT_GRADIENT: StylizedPoseOptions['gradientStops'] = [
            { offset: 0, color: 'rgba(255, 138, 128, 0.95)' },
            { offset: 1, color: 'rgba(168, 216, 185, 0.85)' },
];

export function drawStylizedPose(
  ctx: CanvasRenderingContext2D,
  landmarks: Landmark[],
  canvasWidth: number,
  canvasHeight: number,
  options: StylizedPoseOptions = {}
) {
  const connections: Array<[number, number]> | undefined = (window as any)?.POSE_CONNECTIONS;
  if (!connections || !landmarks) return;

  const {
    visibilityThreshold = 0.25,
    lineWidth = Math.max(canvasWidth, canvasHeight) * 0.01 + 4,
    pointRadius = Math.max(canvasWidth, canvasHeight) * 0.015,
    gradientStops = DEFAULT_GRADIENT,
  } = options;

  const gradient = ctx.createLinearGradient(0, 0, 0, canvasHeight);
  gradientStops.forEach(({ offset, color }) => gradient.addColorStop(offset, color));

  ctx.lineCap = 'round';
  ctx.lineJoin = 'round';
  ctx.lineWidth = lineWidth;
  ctx.strokeStyle = gradient;
  ctx.shadowColor = gradientStops[0]?.color ?? 'rgba(255, 138, 128, 0.45)';
  ctx.shadowBlur = 16;

  connections.forEach(([startIdx, endIdx]) => {
    const start = landmarks[startIdx];
    const end = landmarks[endIdx];
    if (!start || !end) return;

    const startVisible = (start.visibility ?? 1) > visibilityThreshold;
    const endVisible = (end.visibility ?? 1) > visibilityThreshold;
    if (!startVisible || !endVisible) return;

    ctx.beginPath();
    ctx.moveTo(start.x * canvasWidth, start.y * canvasHeight);
    ctx.lineTo(end.x * canvasWidth, end.y * canvasHeight);
    ctx.stroke();
  });

  ctx.shadowBlur = 0;

  landmarks.forEach((point) => {
    if (!point) return;
    if ((point.visibility ?? 1) <= visibilityThreshold) return;

    const x = point.x * canvasWidth;
    const y = point.y * canvasHeight;

    const radial = ctx.createRadialGradient(x, y, 0, x, y, pointRadius);
    radial.addColorStop(0, 'rgba(255, 255, 255, 0.95)');
    radial.addColorStop(1, 'rgba(255, 138, 128, 0.65)');

    ctx.fillStyle = radial;
    ctx.beginPath();
    ctx.arc(x, y, pointRadius, 0, Math.PI * 2);
    ctx.fill();
  });
}


